//
//  OPHUploadRequestExecute.m
//  AtWork2
//
//  Created by lingen on 16/3/31.
//  Copyright © 2016年 Foreverht. All rights reserved.
//

#import "OPHUploadRequestExecute.h"
#import "OPHUploadRequest.h"
#import "OPHResponse.h"
#import <AFNetworking/AFNetworking.h>


@interface OPHUploadRequestExecute()

@property (nonatomic,strong) NSURLSessionUploadTask* uploadTask;

@property (nonatomic,assign) UInt64 refreshMills;

@end

@implementation OPHUploadRequestExecute

/**
 *  开始上传
 */
-(NSURLSessionUploadTask*)startUpload{
    
    NSString* formName = @"file";
    if (_uploadRequest.formName) {
        formName = _uploadRequest.formName;
    }
    NSURL *URL = [NSURL URLWithString:_uploadRequest.url];
    if (URL == nil) {
        URL = [NSURL URLWithString:[_uploadRequest.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        if (URL) {
            _uploadRequest.url = [_uploadRequest.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
     __weak __typeof(self)weakSelf = self;
     NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString: _uploadRequest.url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
          NSString *fileName = weakSelf.uploadRequest.fileName;
          // 百分比解码，否则会由于文件名字过长，导致上传文件失败
          fileName = [fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
          [formData appendPartWithInputStream:weakSelf.uploadRequest.inputStream
                                         name:formName
                                     fileName:fileName
                                       length:weakSelf.uploadRequest.length
                                     mimeType:@"application/octet-stream"];
     } error:nil];
     
     [request setTimeoutInterval:1000 * 60 * 60 * 24];
     __block BOOL cal = NO;
     AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
          
     _uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
          
          if (uploadProgress.fractionCompleted < 1) {
               cal = YES;
          }
          if (weakSelf.progressBlock && cal) {
               //控制下载时间通知的刷新频率
               double progress = uploadProgress.fractionCompleted;
               UInt64 current = [[NSDate date] timeIntervalSince1970] * 1000;
               
               if (current - weakSelf.refreshMills > 500 || progress >= 1.0) {
                    weakSelf.progressBlock(uploadProgress.fractionCompleted);
                    weakSelf.refreshMills = current;
               }
               
          }
          
     } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         int statuCode = (int)httpResponse.statusCode;
         
         OPHResponse* ophResponse  = nil;
         if (statuCode == 200) {
             
             NSData* data = nil;
             if ([responseObject isKindOfClass:[NSData class]]) {
                 data = responseObject;
             }else if ([responseObject isKindOfClass:[NSDictionary class]]){
                 if ([responseObject[@"status"] intValue]!=0) {
                     ophResponse = [OPHResponse errorStatusCodeResponse:[responseObject[@"status"] intValue] error:error];
                     weakSelf.completeBlock(ophResponse);
                     return;
                 }else{
                     data = [NSJSONSerialization dataWithJSONObject:responseObject
                                                            options:NSJSONWritingPrettyPrinted
                                                              error:nil];
                 }
                 
             }
             
             ophResponse = [OPHResponse okReponse:data];
         }else{
             
             ophResponse = [OPHResponse errorStatusCodeResponse:statuCode error:error];
         }
         weakSelf.completeBlock(ophResponse);
     
     }];
    
     [_uploadTask resume];
     return _uploadTask;
}

/**
 *  取消上传
 */
-(void)cancelUpload{
     [_uploadTask cancel];
}

/*
 * 中断上传
 */
-(BOOL)pauseUpload{
     if (_uploadTask.state == NSURLSessionTaskStateRunning) {
          [_uploadTask suspend];
          return YES;
     }
     return NO;
}

/*
 * 重启上传
 */
-(BOOL)resumeUpload{
     if (_uploadTask.state == NSURLSessionTaskStateSuspended) {
          [_uploadTask resume];
          return YES;
     }
     return NO;
}


@end
